Categories
Node.js Tips

Node.js Tips — Express Errors, URLs, Parameters and Writing Files

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

Render Error When Page Not Found

We can render an error message with res.render .

For instance, we can write:

app.use((req, res, next) => {
  res.render('404', { status: 404, url: req.url });
});

to render a 404 error.

'404' is the template name.

the object has the stuff we want to display on the 404 template.

We can also make a generic error handling middleware by writing;

app.use((err, req, res, next) => {
  res.render('500', {
    status: err.status || 500,
    error: err
  });
});

We have err as the first parameter.

We can get the error status code with err.status and we can pass the object off to the 500 page template.

Writing Files in Node.js

We can write files with Node.js with the writeFile , writeFileSync , or a write stream.

For instance, we can write:

const fs = require('fs');

fs.writeFile("/tmp/foo.txt", "hello world", (err) => {
  if (err) {
    return console.log(err);
  }
  console.log("The file was saved!");
});

Or we can writ:

const fs = require('fs');

fs.writeFileSync('/tmp/foo.txt', 'hello world');

They both take the file path and the content as the first 2 arguments.

writeFile also takes a callback that’s called with err if it exists.

To create a write stream, we can write:

const fs = require('fs');
const  stream = fs.createWriteStream("/tmp/foo.txt");
stream.once('open', (fd) => {
  stream.write("hellon");
  stream.write("worldn");
  stream.end();
});

We call createWriteStream to with the file path to write to.

Then we open the stream with stream.once .

Then we start writing with stream.write .

We’ve to close the stream with stream.end .

Get Query String Variables in Express

We can get query string variables with the req.query property.

It has the query string parsed into an object of the key-value pairs.

For instance, we can write:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send(req.query.id);
});

app.listen(3000);

If we have a query string like ?id=10 , then req.query.id is 10.

Retrieve POST Query Parameters in an Express App

We can get POST query parameters with the body-parser package.

To use it, we’ve to install it by running:

npm install --save body-parser

Then we can write:

const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

We import the module so that we can use it.

Then we call bodyParser.json() which returns a middleware to use the middleware.

urlencoded parses URL encoded bodies.

extended set to true means that we can parse JSON bodies in the URL encoded string with it.

Adding CORS Headers to an OPTIONS Route

We can do all the CORDS stuff easily with our own middleware.

For instance, we can write:

const allowCrossDomain = (req, res, next) => {
  res.header('Access-Control-Allow-Origin', 'example.com');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
}

The Access-Control-Allow-Origin header lets the browser know what domains can access the API.

Access-Control-Allow-Methods tells the browser what kind of request it’s allowed to be called.

Access-Control-Allow-Headers tells the browser what kind of content it can send.

An easier way is to use the cors middleware.

To use it, we can run:

npm install cors --save

to install it.

Then we can write:

const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors());
app.options('*', cors());

We use the cors middleware on the whole app with:

app.use(cors());

and we allow the OPTIONs route to be called with:

app.options('*', cors());

How to Get the Full URL in Express

We can use the req.protocol property to get the protocol, which is the http or https part.

Also, we can get the hostname with req.get('host') .

And we get the full URL with the req.originalUrl .

To parse combine the parts into the full URL, we can use the url module.

For instance, we can write:

const requrl = url.format({
  protocol: req.protocol,
  host: req.get('host'),
  pathname: req.originalUrl,
});

We can do that inside the route handler or anywhere else.

Conclusion

We can render an error page by passing in a template and get the status or error we want to display.

The url module can combine the URL parts together.

There are many ways to write files.

CORS can be done by setting a few response headers or using the cors middleware with Express.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *